#include "mainwindow.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QDebug>
#include <QCoreApplication>
#include <QDialog>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QLabel>
#include <QMessageBox>
// 构造函数
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), isLoggedIn(false) {  // 初始化登录状态为 false

    // 创建堆栈窗口
    stackedWidget = new QStackedWidget(this);  // 创建堆栈窗口组件
    setCentralWidget(stackedWidget);           // 设置为主窗口的中心部件

    // 设置登录界面和主界面
    setupLoginUI();  // 初始化登录页面
    setupMainUI();   // 初始化主页面

    // 启动后端进程
    backendProcess = new QProcess(this);  // 创建后端进程对象

    // 连接信号槽 - 处理进程输出
    connect(backendProcess, &QProcess::readyReadStandardOutput,
            this, &MainWindow::onReadyReadStandardOutput);  // 标准输出信号
    connect(backendProcess, &QProcess::readyReadStandardError,
            this, &MainWindow::onReadyReadStandardError);    // 错误输出信号
    connect(backendProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished),
            this, &MainWindow::onProcessFinished);           // 进程结束信号

    // 获取后端可执行文件路径（假设与前端在同一目录）
    QString backendPath = QCoreApplication::applicationDirPath() + "/planner_backend";

    // 启动后端进程
    backendProcess->start(backendPath);
    if (!backendProcess->waitForStarted()) {  // 等待进程启动
        mainOutput->append("Failed to start backend process!");  // 启动失败提示
        return;
    }

    // 发送"run"命令启动后端
    sendCommand("run");
}

// 析构函数
MainWindow::~MainWindow() {
    // 结束时终止后端进程
    if (backendProcess && backendProcess->state() == QProcess::Running) {
        backendProcess->terminate();  // 终止进程
        backendProcess->waitForFinished();  // 等待进程结束
    }
}

// 设置登录界面
void MainWindow::setupLoginUI() {
    loginPage = new QWidget;  // 创建登录页面
    QVBoxLayout *loginLayout = new QVBoxLayout(loginPage);  // 垂直

    // 创建用户名输入框
    QLabel *lblUsername = new QLabel("Username:", loginPage);
    txtUsername = new QLineEdit(loginPage);
    QHBoxLayout *usernameLayout = new QHBoxLayout;
    usernameLayout->addWidget(lblUsername);
    usernameLayout->addWidget(txtUsername);

    // 创建密码输入框
    QLabel *lblPassword = new QLabel("Password:", loginPage);
    txtPassword= new QLineEdit(loginPage);
    txtPassword->setEchoMode(QLineEdit::Password);  // 设置为密码模式
    QHBoxLayout *passwordLayout = new QHBoxLayout;
    passwordLayout->addWidget(lblPassword);
    passwordLayout->addWidget(txtPassword);

    // 创建按钮
    btnRegister = new QPushButton("Register", loginPage);
    btnLogin = new QPushButton("Login", loginPage);
    btnExit = new QPushButton("Exit", loginPage);

    // 添加按钮到布局
    loginLayout->addLayout(usernameLayout);
    loginLayout->addLayout(passwordLayout);
    loginLayout->addWidget(btnRegister);
    loginLayout->addWidget(btnLogin);
    loginLayout->addWidget(btnExit);

    // 将登录页面添加到堆栈窗口
    stackedWidget->addWidget(loginPage);

    // 连接按钮的点击信号到槽函数
    connect(btnRegister, &QPushButton::clicked, this, &MainWindow::onRegisterClicked);
    connect(btnLogin, &QPushButton::clicked, this, &MainWindow::onLoginClicked);
    connect(btnExit, &QPushButton::clicked, this, &MainWindow::onExitClicked);
}

// 设置主界面
void MainWindow::setupMainUI() {
    mainPage = new QWidget;  // 创建主页面
    QVBoxLayout *mainLayout = new QVBoxLayout(mainPage);  // 垂直布局

    // 主输出区域
    mainOutput = new QTextEdit(mainPage);
    mainOutput->setReadOnly(true);  // 设置为只读
    mainLayout->addWidget(mainOutput);  // 添加到布局

    // 后台线程输出区域
    backcheckGroup = new QGroupBox("Backcheck Thread Output", mainPage);  // 分组框
    QVBoxLayout *backcheckLayout = new QVBoxLayout;  // 垂直布局
    backcheckOutput = new QTextEdit(backcheckGroup);  // 文本编辑框
    backcheckOutput->setReadOnly(true);  // 设置为只读
    backcheckLayout->addWidget(backcheckOutput);  // 添加到布局
    backcheckGroup->setLayout(backcheckLayout);  // 设置分组框布局
    mainLayout->addWidget(backcheckGroup);  // 添加到主布局

    // 新增功能按钮区域
    QHBoxLayout *buttonLayout = new QHBoxLayout;  // 水平布局
    btnAddTask = new QPushButton("Add Task", mainPage);
    btnDelTask = new QPushButton("Delete Task", mainPage);
    btnHelp = new QPushButton("Help", mainPage);
    btnShowTasks = new QPushButton("Show Tasks", mainPage);
    btnSave = new QPushButton("Save", mainPage);
    btnLogout = new QPushButton("logout", mainPage);

    buttonLayout->addWidget(btnAddTask);
    buttonLayout->addWidget(btnDelTask);
    buttonLayout->addWidget(btnHelp);
    buttonLayout->addWidget(btnShowTasks);
    buttonLayout->addWidget(btnSave);
    buttonLayout->addWidget(btnLogout);
    mainLayout->addLayout(buttonLayout);  // 添加到主布局

    // 连接新增按钮的信号槽
    connect(btnAddTask, &QPushButton::clicked, this, &MainWindow::onAddTaskClicked);
    connect(btnDelTask, &QPushButton::clicked, this, &MainWindow::onDelTaskClicked);
    connect(btnHelp, &QPushButton::clicked, this, &MainWindow::onHelpClicked);
    connect(btnShowTasks, &QPushButton::clicked, this, &MainWindow::onShowTasksClicked);
    connect(btnSave,&QPushButton::clicked,this,&MainWindow::onSaveClicked);
    connect(btnLogout,&QPushButton::clicked,this,&MainWindow::onLogoutClicked);

    // 命令输入区域
    QHBoxLayout *commandLayout = new QHBoxLayout;  // 水平布局
    txtCommand = new QLineEdit(mainPage);  // 命令输入框
    btnSend = new QPushButton("Send", mainPage);  // 发送按钮
    commandLayout->addWidget(txtCommand, 4);  // 输入框占4份空间
    commandLayout->addWidget(btnSend, 1);     // 按钮占1份空间
    mainLayout->addLayout(commandLayout);     // 添加到主布局

    // 将主页面添加到堆栈窗口
    stackedWidget->addWidget(mainPage);

    // 连接信号槽
    connect(btnSend, &QPushButton::clicked, this, &MainWindow::onCommandEntered);
    connect(txtCommand, &QLineEdit::returnPressed, this, &MainWindow::onCommandEntered);
}

// 注册按钮点击事件
void MainWindow::onRegisterClicked() {
    if(txtUsername->text().trimmed().isEmpty()||txtPassword->text().trimmed().isEmpty())
        QMessageBox::warning(this, "Error", "Username and password are required!");
    sendCommand("register");  // 发送注册命令
    sendCommand(txtUsername->text());
    sendCommand(txtPassword->text());
    txtPassword->clear();  // 清空密码框
    txtUsername->clear();
}

// 登录按钮点击事件
void MainWindow::onLoginClicked() {
    if(txtUsername->text().trimmed().isEmpty()||txtPassword->text().trimmed().isEmpty())
        QMessageBox::warning(this, "Error", "Username and password are required!");
    sendCommand("login");  // 发送登录命令
    sendCommand(txtUsername->text());
    sendCommand(txtPassword->text());
    txtPassword->clear();  // 清空密码框
    txtUsername->clear();
}

// 退出按钮点击事件
void MainWindow::onExitClicked() {
    sendCommand("exit");  // 发送退出命令
    close();  // 关闭应用程序
}

// 命令输入事件
void MainWindow::onCommandEntered() {
    QString command = txtCommand->text();  // 获取输入的命令
    txtCommand->clear();  // 清空输入框

    if (command == "logout") {
        isLoggedIn = false;  // 更新登录状态
        stackedWidget->setCurrentIndex(0);  // 切换回登录界面
    }

    sendCommand(command);  // 发送命令到后端
}

// 发送命令到后端进程
void MainWindow::sendCommand(const QString &cmd) {
    if (backendProcess && backendProcess->state() == QProcess::Running) {
        // 将命令转换为字节数组并添加换行符
        backendProcess->write((cmd + "\n").toUtf8());
    }
}

// 处理标准输出
void MainWindow::onReadyReadStandardOutput() {
    QByteArray output = backendProcess->readAllStandardOutput();  // 读取所有标准输出
    QString outputStr = QString::fromUtf8(output);  // 转换为字符串


    mainOutput->append(outputStr);  // 其他输出添加到主输出区

    // 检查登录成功
    if (outputStr.contains("welcome")) {
        // 切换到主界面
        stackedWidget->setCurrentIndex(1);  // 切换到堆栈窗口的第1页（主页面）
        isLoggedIn = true;  // 更新登录状态
    }
}

// 处理标准错误输出
void MainWindow::onReadyReadStandardError() {
    QByteArray error = backendProcess->readAllStandardError();  // 读取所有错误输出
    backcheckOutput->append(QString::fromUtf8(error));  // 添加到后台输出区域
}

// 进程结束事件处理
void MainWindow::onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus) {
    // 在输出区域显示进程退出信息
    mainOutput->append(QString("Backend process exited with code %1").arg(exitCode));
}

// 新增功能按钮的实现

// 添加任务按钮点击事件
void MainWindow::onAddTaskClicked() {
    QDialog dialog(this);
    dialog.setWindowTitle("Add New Task");

    QFormLayout form(&dialog);

    // 创建输入字段
    QLineEdit *txtName = new QLineEdit(&dialog);
    QLineEdit *txtStartTime = new QLineEdit(&dialog);
    QLineEdit *txtNoticeTime = new QLineEdit(&dialog);
    QLineEdit *txtLevel = new QLineEdit("1", &dialog);  // 默认优先级为1
    QLineEdit *txtElement = new QLineEdit("entertainment", &dialog);  // 默认属性

    form.addRow("Task Name:", txtName);
    form.addRow("Start Time (YYYYMMDDHHMM):", txtStartTime);
    form.addRow("Notice Time (YYYYMMDDHHMM):", txtNoticeTime);
    form.addRow("Priority Level (1-3):", txtLevel);
    form.addRow("Category:", txtElement);

    // 添加确定和取消按钮
    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
                               Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);

    QObject::connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    QObject::connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        // 检查必填字段
        if (txtName->text().trimmed().isEmpty() ||
            txtStartTime->text().trimmed().isEmpty() ||
            txtNoticeTime->text().trimmed().isEmpty()) {
            QMessageBox::warning(this, "Error", "Task name and time fields are required!");
            return; // 阻止发送命令
        }

        QString command = QString("addtask %1 %2 %3 %4 %5")
                              .arg(txtName->text().trimmed())
                              .arg(txtStartTime->text().trimmed())
                              .arg(txtNoticeTime->text().trimmed())
                              .arg(txtLevel->text().trimmed())
                              .arg(txtElement->text().trimmed());
        sendCommand(command);
    }
}

// 删除任务按钮点击事件
void MainWindow::onDelTaskClicked() {
    QDialog dialog(this);
    dialog.setWindowTitle("Delete Task");

    QFormLayout form(&dialog);

    QLineEdit *txtId = new QLineEdit(&dialog);
    form.addRow("Task ID to delete:", txtId);

    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
                               Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);

    QObject::connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    QObject::connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        sendCommand("deltask " + txtId->text());
    }
}

// 帮助按钮点击事件
void MainWindow::onHelpClicked() {
    sendCommand("help");
}

// 显示任务按钮点击事件
void MainWindow::onShowTasksClicked() {
    QDialog dialog(this);
    dialog.setWindowTitle("Show Tasks");

    QFormLayout form(&dialog);

    QLineEdit *txtModel = new QLineEdit("day", &dialog);  // 默认模式为day
    form.addRow("View Mode (day/month/all):", txtModel);

    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
                               Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);

    QObject::connect(&buttonBox, &QDialogButtonBox::accepted, &dialog, &QDialog::accept);
    QObject::connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    if (dialog.exec() == QDialog::Accepted) {
        sendCommand("showtasks " + txtModel->text());
    }
}
void MainWindow::onSaveClicked(){
    sendCommand("save");
}
void MainWindow::onLogoutClicked(){
    sendCommand("logout");
    isLoggedIn = false;     // 更新登录状态
    stackedWidget->setCurrentIndex(0);  // 切换回登录界面

    // 清空输出区域
    mainOutput->clear();
    backcheckOutput->clear();
}
